<?php

/**
 * ECSHOP 商品页
 * ============================================================================
 * * 版权所有 2005-2012 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: liuhui $
 * $Id: order.php 15013 2008-10-23 09:31:42Z liuhui $
*/

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH . 'includes/lib_order.php');
require(ROOT_PATH . 'includes/lib_payment.php');

$flow_type = 0;
$_LANG['gram'] = '克';
$_LANG['kilogram'] = '千克';

if( isset($_POST['item_info']) && $_POST['item_info'] ) $_SESSION['item_info'] = $_POST['item_info'];
$order_id = isset($_GET['order_id'])? $_GET['order_id'] : '';

if ($_SESSION['user_id'] > 0)
{
    if( $_SESSION['email'] == "0" ) $_SESSION['email'] = '';
    $smarty->assign('user_info', $_SESSION);
}

if( @$_SESSION['item_info'] ){

    $item_data = $_SESSION['item_info'];
    if(ini_get("magic_quotes_gpc")=="1") {
        $item_data=stripslashes($item_data);
    }else{
        ini_set("magic_quotes_gpc", 1);
        $item_data=stripslashes($item_data);
    }

    $item_data = json_decode( $item_data, true );

    if( $item_data['fangan'] ){
        $fa_sql="select * from ".$ecs->table('category')." category where cat_id=".$item_data['fangan'];
        $fa_info=$db->getAll($fa_sql);
        $item_attr_info['学习方案'] = $fa_info[0]['cat_name'];
    }

    if( $item_data['nianji'] ){
        $nj_sql="select * from ".$ecs->table('category')." category where cat_id=".$item_data['nianji'];
        $nj_info=$db->getAll($nj_sql);
        $item_attr_info['年级'] = $nj_info[0]['cat_name'];
    }


    if( $item_data['attr_id'] && $item_data['goods_id'] ){
        $attr_sql="select * from ".$ecs->table('goods_attr')." goods_attr where goods_attr_id='".$item_data['attr_id']."'";
        $attr_info=$db->getAll($attr_sql);
        $item_attr_info['课时'] = $attr_info[0]['attr_value'];
        $sql="select * from ".$ecs->table('goods')." goods where goods_id='".$item_data['goods_id']."'";
        $item=$db->getAll($sql);

        $item_info['price'] = $attr_info[0]['attr_price'];
        $item_info['goods_name'] = $item[0]['goods_name'];
        $item_info['goods_img'] = $item[0]['goods_img'];
    }

    if( $item_data['only_price'] ){
        $sql="select * from ".$ecs->table('goods')." goods where cat_id='".$item_data['nianji']."'";
        $goods_info=$db->getAll($sql);
        $item_info['price'] = $goods_info[0]['market_price'];
        $item_info['goods_name'] = $goods_info[0]['goods_name'];
        $item_info['goods_img'] = $goods_info[0]['goods_img'];
    }

    if( $item_data['is_vip'] ) $item_attr_info['VIP'] = '五星名师';

    $smarty->assign( 'item_info', $item_info );
    $smarty->assign( 'item_attr_info', $item_attr_info );    
}


if($_REQUEST['act'] == 'order_lise')
{

    if( !$_SESSION['item_info'] ){
        if( isset($_SERVER['HTTP_REFERER']) ) ecs_header("Location: ".$_SERVER['HTTP_REFERER']."\n");
        else ecs_header("Location: /\n");
        exit;
    }


    $pay_way = array('online'=>'在线支付','credit_cart'=>'信用卡分期','post_office'=>'邮局汇款','store'=>'门店付款');
    $payment = isset($_GET['payment'])?$_GET['payment']:($_SESSION['pay_en_name']?$_SESSION['pay_en_name']:'online');

    if( isset($pay_way[$payment]) ){
        $pay_info['en_name'] = $payment;
        $pay_info['cn_name'] = $pay_way[$payment];
    }else{
        $pay_info['en_name'] = 'online';
        $pay_info['cn_name'] = '在线支付';
    }

    $_SESSION['pay_en_name'] = $pay_info['en_name'];
    $_SESSION['pay_cn_name'] = $pay_info['cn_name'];

    $link = '/mobile/order.php?act=done';
    //if( $payment == 'post_office' || $payment == 'store' ) $link = '/mobile/order.php?act=order_deal';
    
    $smarty->assign( 'link',  $link );
    $smarty->assign( 'pay_info',  $pay_info );
    $smarty->display('order.html');
    exit;

}else if( $_REQUEST['act'] == 'order_deal' ){

    $smarty->display('order_deal.html');

}
elseif($_REQUEST['act'] = 'done')
{
    /*------------------------------------------------------ */
    //-- 完成所有订单操作，提交到数据库
    /*------------------------------------------------------ */
    include_once('includes/lib_clips.php');
    $order_id = $order_id?$order_id:(isset($_SESSION['new_order_id'])?$_SESSION['new_order_id']:'');

    if( $order_id && !$_SESSION['item_info'] ){
        $order = order_info( $order_id );
        if( !$order ){
            if( isset($_SERVER['HTTP_REFERER']) ) ecs_header("Location: ".$_SERVER['HTTP_REFERER']."\n");
            else ecs_header("Location: /\n");
            exit;
        }
    }else{

        if( !$_SESSION['item_info'] ){
            if( isset($_SERVER['HTTP_REFERER']) ) ecs_header("Location: ".$_SERVER['HTTP_REFERER']."\n");
            else ecs_header("Location: /\n");
            exit;
        }

        $consignee = get_consignee($_SESSION['user_id']);

        $order = array(
            'shipping_id'     => 0,
            'pay_id'          => '0',
            'pack_id'         =>  0,
            'card_id'         =>  0,
            'card_message'    => '',
            'surplus'         => 0.00,
            'integral'        => 0,
            'bonus_id'        => 0,
            'need_inv'        => 0,
            'inv_type'        => '',
            'inv_payee'       => '',
            'inv_content'     => '',
            'postscript'      => '',
            'how_oos'         => '',
            'need_insure'     => 0,
            'user_id'         => $_SESSION['user_id'],
            'add_time'        => gmtime(),
            'order_status'    => 1,
            'shipping_status' => SS_UNSHIPPED,
            'pay_status'      => PS_UNPAYED,
            'agency_id'       => get_agency_by_regions(array($consignee['country'], $consignee['province'], $consignee['city'], $consignee['district']))
            );

            $order['extension_code'] = '';
            $order['extension_id'] = 0;
            $order['surplus']  = 0;
            $order['integral'] = 0;


        /* 订单中的商品 */
        $cart_goods = cart_goods($flow_type);


        /* 收货人信息 */
        if( $consignee ){
            foreach ($consignee as $key => $value)
            {
                $order[$key] = addslashes($value);
            }
        }

        /* 订单中的总额 */
        $total = order_fee($order, $cart_goods, $consignee);

        $order['bonus']        = $total['bonus'];
        $order['goods_amount'] = number_format($item_info['price'], 2, '.', '');
        $order['discount']     = $total['discount'];
        $order['surplus']      = $total['surplus'];
        $order['tax']          = $total['tax'];
        $order['shipping_name'] = '';
        $order['shipping_fee'] = $total['shipping_fee'];
        $order['insure_fee']   = $total['shipping_insure'];
        $order['pay_name'] = $_SESSION['pay_cn_name'];
        $order['pay_fee'] = 0;
        $order['cod_fee'] = 0;
        $order['integral_money']   = 0;
        $order['integral']         = 0;
        $order['integral_money']   = 0;
        $order['integral']         = 0;
        $order['from_ad']          = !empty($_SESSION['from_ad']) ? $_SESSION['from_ad'] : '0';
        $order['referer']          = !empty($_SESSION['referer']) ? addslashes($_SESSION['referer']) : '';
        $order['order_amount']  = number_format($item_info['price'], 2, '.', '');
        $order['extension_code'] = 0;
        $order['extension_id'] = 0;

        /* 插入订单表 */
        $error_no = 0;
        do
        {
            $order['order_sn'] = get_order_sn(); //获取新订单号
            $GLOBALS['db']->autoExecute($GLOBALS['ecs']->table('order_info'), $order, 'INSERT');

            $error_no = $GLOBALS['db']->errno();

            if ($error_no > 0 && $error_no != 1062)
            {
                die($GLOBALS['db']->errorMsg());
            }
        }
        while ($error_no == 1062); //如果是订单号重复则重新提交数据

        $new_order_id = $db->insert_id();
        $order['order_id'] = $new_order_id;
        $_SESSION['new_order_id'] = $new_order_id;
        
        $item_attr = '';
        foreach ($item_attr_info as $key => $value) $item_attr .= $key.":".$value."\r\n";

        /* 插入订单商品 */
        $sql = "INSERT INTO " . $ecs->table('order_goods') . "( " .
                    "order_id, goods_id, goods_name, goods_sn, goods_number, market_price, ".
                    "goods_price, goods_attr, is_real, extension_code, parent_id, is_gift, goods_attr_id) ".
                " SELECT '$new_order_id', goods_id, goods_name, goods_sn, goods_number, ".$item_info['price'].", ".$item_info['price'].", '".$item_attr."', 1, 0, 0, 0, 0 FROM " .$ecs->table('goods') .
                " WHERE goods_id = '".$item_data['goods_id']."'";
        $db->query($sql);
        $_SESSION['item_info'] = '';
        $smarty->assign('total',  $total);
    }


    /* 订单信息 */
    $smarty->assign('order',      $order);

    if ($_SESSION['user_id'] > 0)
    {
        $smarty->assign('user_name', $_SESSION['user_name']);
    }
    $smarty->assign('footer', get_footer());
    $smarty->assign('tips', $tips);

    if( $_SESSION['pay_en_name'] == 'online' ) $smarty->display('order_online.html');
    else if( $_SESSION['pay_en_name'] == 'post_office' || $_SESSION['pay_en_name'] == 'store' ) $smarty->display('order_deal.html');
    else  $smarty->display('order_post_office.html');
    exit;

}

function flow_available_points()
{
    $sql = "SELECT SUM(g.integral * c.goods_number) ".
            "FROM " . $GLOBALS['ecs']->table('cart') . " AS c, " . $GLOBALS['ecs']->table('goods') . " AS g " .
            "WHERE c.session_id = '" . SESS_ID . "' AND c.goods_id = g.goods_id AND c.is_gift = 0 AND g.integral > 0 " .
            "AND c.rec_type = '" . CART_GENERAL_GOODS . "'";

    $val = intval($GLOBALS['db']->getOne($sql));

    return integral_of_value($val);
}

/**
 * 检查订单中商品库存
 *
 * @access  public
 * @param   array   $arr
 *
 * @return  void
 */
function flow_cart_stock($arr)
{
    foreach ($arr AS $key => $val)
    {
        $val = intval(make_semiangle($val));
        if ($val <= 0)
        {
            continue;
        }

        $sql = "SELECT `goods_id`, `goods_attr_id`, `extension_code` FROM" .$GLOBALS['ecs']->table('cart').
               " WHERE rec_id='$key' AND session_id='" . SESS_ID . "'";
        $goods = $GLOBALS['db']->getRow($sql);

        $sql = "SELECT g.goods_name, g.goods_number, c.product_id ".
                "FROM " .$GLOBALS['ecs']->table('goods'). " AS g, ".
                    $GLOBALS['ecs']->table('cart'). " AS c ".
                "WHERE g.goods_id = c.goods_id AND c.rec_id = '$key'";
        $row = $GLOBALS['db']->getRow($sql);

        //系统启用了库存，检查输入的商品数量是否有效
        if (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] != 'package_buy')
        {
            if ($row['goods_number'] < $val)
            {
                show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'],
                $row['goods_number'], $row['goods_number']));
                exit;
            }

            /* 是货品 */
            $row['product_id'] = trim($row['product_id']);
            if (!empty($row['product_id']))
            {
                $sql = "SELECT product_number FROM " .$GLOBALS['ecs']->table('products'). " WHERE goods_id = '" . $goods['goods_id'] . "' AND product_id = '" . $row['product_id'] . "'";
                $product_number = $GLOBALS['db']->getOne($sql);
                if ($product_number < $val)
                {
                    show_message(sprintf($GLOBALS['_LANG']['stock_insufficiency'], $row['goods_name'],
                    $row['goods_number'], $row['goods_number']));
                    exit;
                }
            }
        }
        elseif (intval($GLOBALS['_CFG']['use_storage']) > 0 && $goods['extension_code'] == 'package_buy')
        {
            if (judge_package_stock($goods['goods_id'], $val))
            {
                show_message($GLOBALS['_LANG']['package_stock_insufficiency']);
                exit;
            }
        }
    }

}
?>